<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片区域-->
    <el-card class="box-card">
      <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
      <!--角色列表-->
      <el-table :data="rolesList" border scripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,k1) in scope.row.children"
              :key="item1.id"
              :style="{ 'border-bottom': '1px solid rgb(235,238,245)','border-top':k1===0?'1px solid rgb(235,238,245)':'' }"
            >
              <el-col :span="5">
                <el-tag closable @close="delRight(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2,k2) in item1.children"
                  :key="item2.id"
                  :style="{ 'border-top': k2!==0?'1px solid rgb(235,238,245)':''}"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delRight(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      @close="delRight(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRole(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--角色分配权限弹层-->
      <el-dialog title="角色分配" :visible.sync="setRightDialogVisible" width="50%" top="185px">
        <el-tree
          :data="rightsList"
          :props="rightsListProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defaultCheckedKeys"
          ref="rightRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="setRight">确 定</el-button>
        </span>
      </el-dialog>

      <!--添加角色弹层-->
      <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%"
        top="185px"
        :before-close="addDialogCloseBefore"
        @close="addDialogClose"
      >
        <!--添加角色自带验证的表单区域-->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogClose">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>

      <!--修改角色弹层-->
      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        top="185px"
        :before-close="editDialogCloseBefore"
        @close="editDialogClose"
      >
        <!--修改角色自带验证的表单区域-->
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogClose">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /** 角色分配权限1 */
      // 弹框默认不显示
      setRightDialogVisible: false,
      // 权限列表
      rightsList: [],
      rightsListProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认拥有的第3 级别权限的ids数组
      defaultCheckedKeys: [],
      // 被分配权限的角色id
      roleId: '',
      /** 角色分配权限2 */

      // 角色列表
      rolesList: [],
      // 添加角色 弹框默认不显示
      addDialogVisible: false,
      // 添加角色表单数据对象
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色 表单数据验证
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 修改角色 弹框默认不显示
      editDialogVisible: false,
      // 修改角色表单数据对象
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      // 修改角色 表单数据验证
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    /** 角色分配权限1 */
    // 展示弹框
    async showSetRightDialog(role) {
      this.setRightDialogVisible = true
      this.roleId = role.id
      // 获得可供选取的tree型权限信息
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取tree权限列表失败',
          type: 'error',
          duration: 1000
        })
      }
      this.rightsList = res.data
      // 获得当前角色拥有的三级权限id的集合数组
      const keys = []
      this.getLeafIds(role, keys)
      this.defaultCheckedKeys = keys
    },
    // 通过给定的角色信息，获取其拥有的全部三级权限ids的数组
    // node被处理的权限对象，keyArr收集三级权限的数组
    getLeafIds(node, keyArr) {
      if (!node.children) {
        return keyArr.push(node.id)
      }
      node.children.forEach(item => this.getLeafIds(item, keyArr))
    },
    // 给角色分配权限服务器端处理
    async setRight() {
      // 获取权限权限的id
      const k1 = this.$refs.rightRef.getCheckedKeys()
      // 获取半选权限的id
      const k2 = this.$refs.rightRef.getHalfCheckedKeys()

      // 拼接出所有被勾选出权限的ids字符串
      const idsstr = [...k1, ...k2].join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idsstr }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          message: '分配权限失败',
          type: 'error',
          duration: 1000
        })
      }

      this.$message({
        message: '分配权限成功',
        type: 'success',
        duration: 1000
      })
      // 刷新角色和对应的权限
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    /** 角色分配权限2 */

    /** 角色删除权限1 */
    // 根据权限id，删除指定角色对应的权限
    async delRight(role, rightid) {
      const cfm = await this.$confirm('确定要删除该权限么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rightid}`
        )
        if (res.meta.status !== 200) {
          return this.$message({
            message: '删除失败！',
            type: 'error',
            duration: 1000
          })
        }

        this.$message({
          message: '删除成功！',
          type: 'success',
          duration: 1000
        })
        // 重新渲染数据
        role.children = res.data
      }
    },
    /** 角色删除权限2 */

    /** ******删除1*********/
    async delRole(id) {
      const cfm = await this.$confirm('确定要删除该角色么?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) {
          return this.$message({
            message: '删除角色失败',
            type: 'error',
            duration: 1000
          })
        } else {
          this.getRolesList()
          return this.$message({
            message: '角色已经删除',
            duration: 1000
          })
        }
      }
    },
    /** ******删除2*********/
    /** ******修改1*********/
    // 修改需要的事件方法
    async showEditDialog(id) {
      // 展示弹框
      this.editDialogVisible = true
      // 获得被修改角色信息
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取角色失败',
          type: 'error',
          duration: 1000
        })
      }
      this.editForm = res.data
    },
    // 修改角色需要的事件方法
    // 添加弹框 点击旁地 关闭
    editDialogCloseBefore(done) {
      this.$refs.editFormRef.resetFields()
      done()
    },
    // 修改弹框 点击取消 关闭
    editDialogClose() {
      this.editDialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    // 收集数据存储入库
    editRole() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'roles/' + this.editForm.roleId,
            this.editForm
          )

          if (res.meta.status !== 200) {
            this.$message({
              message: '修改失败',
              type: 'error',
              duration: 1000
            })
          }

          // 关闭弹框
          this.editDialogClose()
          // 页面刷新
          this.getRolesList()
          // 提示
          this.$message({
            message: '修改成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    /** ******修改2*********/
    // 添加角色需要的事件方法
    // 添加弹框 点击旁地 关闭
    addDialogCloseBefore(done) {
      this.$refs.addFormRef.resetFields()
      done()
    },
    // 添加弹框 点击取消 关闭
    addDialogClose() {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色 到服务器端处理
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('roles', this.addForm)
          if (res.meta.status !== 201) {
            return this.$message({
              message: '添加角色失败',
              type: 'error',
              duration: 1000
            })
          }
          // 关闭弹框
          this.addDialogClose()
          // 页面刷新
          this.getRolesList()
          this.$message({
            message: '添加角色成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    // 获取角色列表信息
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取角色列表失败',
          type: 'error',
          duration: 1000
        })
      }
      this.rolesList = res.data
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px 5px;
}
.el-row{
  display:flex;
  align-items:center;
}
</style>
